Flash Article

Stepping into the New Macromedia Flash MX 2004 Component Structure


Table of Contents

  1. Introduction
  2. Moving Up to v2 Components
  3. Choosing Your Upgrade Path
  4. Upgrading Your Applications
  5. Search and Destroy

Upgrading Your Applications

If you want to take an existing project and upgrade all the v1 components to v2 components, you have a bit of work in front of you. However, even if you're starting a project from scratch you'll have to learn the v2 approach as well as the new syntax. This section explains the process involved for both cases.

Physically Replace v1 Components

Upgrading your v1 components involves swapping each instance on the Stage with a replacement. This is true whether you're using v2 components that ship with Flash MX 2004 or the rereleased versions of v1 components that come with DRK Volume 5. Unfortunately, you can't just select your old instance and click the Properties panel's Swap button and then point to a replacement—only the same generation components are listed!

It comes down to the following three steps:

  1. Record the position and dimensions of your existing component, then position and scale the replacement the same. (Move the old one off to the side instead of removing it right away.)
  2. Give the new component the same instance name as the old one. (Change the name of the old one so that if you don't remove it right away you don't have any conflicts.)
  3. Provided you've set parameters for the old component manually (through the Properties panel), attempt to populate the new one the same way. However, if you're upgrading to v2 components (that is, you're not simply using the new v1 replacements that come with DRK Volume 5), then you'll find not every setting in v1 components translates to a parameter in the new ones. For example, the old v1 PushButton component has a ClickHandler parameter but you won't find that listed in the v2 Button component. Ultimately you should set all such values entirely using a script. For now, however, just record the values you have set in the old component before you delete the instance on the Stage.

If you're using the v1 replacements on DRK Volume 5, then you're done. If you're using the v2 components you'll need to update your code so it uses the new syntax. That is, search through all your ActionScript and update old style code with the new style. The next section covers the main changes.

Know the Syntax Changes

Using the v2 components involves the same old ActionScript you know and love—it's just that a lot of conveniences have been added. Of course, this also means some of your old code has to be updated. Understanding how the syntax has changed is important both for updating old applications as well as creating new ones.

Direct Access to Properties: The biggest syntactical change is that many component parameters are directly exposed as properties. In version 1 of the component structure you nearly always used methods to access or change a property. For example, myButton.setLabel("click me") is now achieved using myButton.label="click me". Although this change may not immediately blow you away, you should see the advantage in the following example:

//old way:
myList.setSelectedIndex(myList.getSelectedIndex()+1);

//new way:
myList.selectedIndex++;

By exposing the selectedIndex property the need for two methods is gone.

Event Listeners Not Click Handlers: Another important change is the way you tie components to custom scripts. That is, if you wanted a v1 component button to trigger a function you would set the button's ClickHandler parameter. For example: myButton.setClickHandler("myFunction"); The biggest hassle with this was having to know first whether the component had a click handler (like with buttons) or a change handler (as with the ComboBox or ListBox components). In addition, each component had just one event you could trap. The v2 components now use event listeners. The syntax is only slightly different, but vastly improved. Here are two simple versions—the second one being a bit more extensible:

myFunction=function(){
  trace("they clicked my button");
}
myButton.addEventListener("click", myFunction);

myObject=new Object();
myObject.click=function(){
  trace("they clicked my other button");
}
myOtherButton.addEventListener("click", myObject);

Note that unlike the setClickHandler() function (which accepted a string or the name of your custom function), addEventListener() identifies a function or an object containing callback events by reference (no quote marks around the name). Although the second example seems slightly redundant (with "click" appearing in two places), it does enable you to consolidate more handlers in a single object. For example, the v2 components support multiple events. You can add to the myObject instance by defining more callbacks:

myObject.load=function(){
  //do something
}
myObject.unload=function(){
  //do something
}
myOtherButton.addEventListener("load", myObject);
myOtherButton.addEventListener("unload", myObject);

Here's a quick way to learn the events each component supports. Just select the component instance and type "on(" . You'll immediately see a code hint with all the events (such as click, load, and unload). It's not a best practice to leave code right on the instance this way, but you can use this technique and then delete what you typed.

Referencing the Component That Triggers Your Handler: Most likely you'll want to find a way to let multiple component instances trigger the same script—but then once inside that handler, sort out which instance did the triggering. For example, if you have three Radio Button instances (say small, medium, large) you don't need three separate functions. You can achieve this both in v1 and v2 components—the difference, however, is the way you get a reference to the component that triggered your handler.

Specifically, ClickHandler and ChangeHandler functions in v 1 components received a reference to the component instance where v2 event listeners receive an object with many properties including a target property that contains a reference to the component. Here's the old and new way side by side:

//v1 
small_rb.setClickHandler("myFunction");
medium_rb.setClickHandler("myFunction");
large_rb.setClickHandler("myFunction");
myFunction=function(param){
  trace("the button clicked was "+param);
};

//v2 
small_rb.addEventListener("click", myFunction);
medium_rb.addEventListener("click", myFunction);
large_rb.addEventListener("click", myFunction);
myFunction=function(param){
  trace("the button clicked was "+param.target);
};

You'll find that the new parameter contains other interesting properties as well. In addition, because the target property is a reference to the calling component, you can use target as if it was the component (accessing or setting its properties, for example).

Specific Changes in Detail

The three syntax changes covered above go a long way to bringing you up to speed with the new architecture. There are a few—more specific—tasks that come in handy as you get into more detailed features. These revolve around using DataProviders, cell renderers, and scrolling text.

DataProviders: In v1 components the DataProvider component was a special class based on the Array object. Basically, you stored into a variable an array of identically structured ActionScript objects (each with the same named properties). Then, you associate a List, ComboBox, or DataGrid component with that variable. Magically, the component gets populated and it even visually updates any time the source data is modified.

The v2 components still support DataProvider instances, but they're a bit easier to manage. First, they are arrays that simply get treated like DataProviders. The difference is that you don't begin by creating a new DataProviderClass instance; rather, you just make an new array. You can populate that array however you want, but should consider using addItem() instead of the traditional push() method. That's because after you associate a component with that DataProvider variable you can only use DataProvider methods—not Array methods.

In practice the only obvious difference is that you're given direct access to the dataProvider property instead of using the old setDataProvider() method. Here are two examples to clarify things:

//v1
myDP=new DataProviderClass();
myDP.addItem({label:"one", data:1});
myDP.addItem({label:"two", data:2});
myDP.addItem({label:"three", data:3});

my_cb.setDataProvider(myDP);
my_cb.setChangeHandler("doChangeCombo");

function doChangeCombo(theCB){
  trace("selected data is "+theCB.getSelectedItem().data);
}

//v2
myDP=new Array();
myDP.addItem({label:"one", data:1});
myDP.addItem({label:"two", data:2});
myDP.addItem({label:"three", data:3});

my_cb.dataProvider=myDP;
my_cb.addEventListener("change", doChangeCombo);

function doChangeCombo(obj){
  trace("selected data is "+obj.target.selectedItem.data);
}

Note that in version 2 of the component structure you begin with an actual array. This makes it easier to integrate with your stored data because an array is a much more common data type. The rest is pretty much the same. Naturally, because these are v2 components, you set the DataProvider variable directly as a property in v2 components and define the change differently. Finally, realize that many components, including the items inside ComboBox components, have two values: the label (that is what the user sees) and the data (accessible through a script, but mainly a place where you store any data you want).

By the way, if you're adding items to a DataProvider component that will become the source for a DataGrid component you can have as many properties as you want—just as long as each item added has the same properties. These property names become your column names.

Cell Renderers: Cell renderers are a way for you to override exactly how data appearing inside a cell of the DataGrid (or List) component shall appear. That is, normally, cells display the value for each item in each row of your data. However, say you want to have bold text in one column? Or, perhaps an icon or even animated clip based on the value? In Figure2 you can see the status column displays one of four icons. The way you can do this is by defining a cell renderer.

Figure 2.

Figure 2. Adding an icon using the cell renderer results in a more visually pleasing and usable DataGrid component.

The way you defined cell renderers in v1 components was not super difficult—mainly you had to make a clip that defined a setValue() method inside of which you wrote all the code responsible for how the cell's data would be translated to some graphic form. All this code had to be stuffed between #initclip and #endinitclip to ensure it would execute before the clip instantiated. Finally, this clip needed to be associated with a particular column in your DataGrid component using setCellSymbol().

The cell renderer code is not that much different in v2 components. However, it's all handled through nice clean class files that are extendable. A better word might be unlimited, because by extending classes you can add any functionality you want. Just so you can see a starter skeleton on which you can add later, check out the following example.

  1. You need a clip containing a dynamic text field instance named my_txt . Select this clip in the Library and choose Linkage. Set the Linkage to myLinkage and the AS2.0 Class to MyRenderer as shown in Figure 3. Case sensitivity does matter—and, by style, classes begin uppercase. Also, even though the class files use the .as extension, don't use the extension when pointing to the class file.

    Figure 3.

    Figure 3. You want to set the Linkage and point to an AS2.0 Class file.

  2. Drag a List component with the instance name myList to the Stage. Put this code in the first keyframe:

    dp=new Array();
    dp.addItem({label: "one", data:1, extra:0xFF0000, state:true});
    dp.addItem({label: "two", data:2, extra:0x00FF00, state:false});
    dp.addItem({label: "three", data:3, extra:0x0000FF, state:true});
    
    myList.dataProvider=dp;
    myList.cellRenderer = "myLinkage";
    

    Note: To set the cell renderer for a column in a DataGrid use: myDataGrid.getColumnAt(0).cellRenderer="myLinkage" (but replace the 0 with which ever column you want to affect).

  3. Put this code in ActionScript file (that is a text file) named MyRenderer.as:

    class MyRenderer extends MovieClip
    {
      var my_txt:TextField;
    
      function MyRenderer(){}
    
      function setValue(theValue:String, theItem:Object, selected:String):Void
      {
        my_txt.text=theValue + " -- " + selected;
      } 
    }
    

The setValue() function is built into the List class and here, you're simply overriding it so that it does what you want. When you test the movie the labels show but so does the current state of the selected value (see Figure 4).

Figure 4

Figure 4. We're populating our own text field with information received from the setValue() method.

Normally the List component displays the label property and maintains the data property. This DataProvider instance also has a property called extra. You're given a reference to the item (that is, the whole row) in the second parameter of the setValue() method. For example, you can access the extra property even though setValue() is primarily intended to display the label. Consider this update to that method:

function setValue(theValue:String, theItem:Object, selected:String):Void
{
  my_txt.text=theValue + " -- " + selected;
  my_txt.background=true;
  my_txt.backgroundColor=theItem.extra; 
  if(theItem==undefined){
    my_txt._visible=false;
  }
}

That if statement makes sure you don't see any text for the blank rows, because the row might be visible.

Basically, any sort of display controls you want, you do it in the setValue() method. You can display icons or parse and format text—whatever you want. Notice that you must declare any objects that you intend to address up at the top of the class (that is, where I use var my_txt ).

There are a few other built-in methods that you can override in the renderer.

If you intend to nest components inside of a cell (say, to display a check box instead of the word "true" or "false") you should use the createObject() method (which is similar to the attachMovie() method but just for making components) within the renderer's createChildren() method. That is, you don't want to place the component right inside the movie clip (the way I did with the my_txt field).

Here's a new version of the MyRenderer.as file—just be sure to place in your movie an instance of the CheckBox component. You can drag one to the Stage and then delete it—so that it's safe in your Library (just don't put it in the movie clip with the my_txt field):

import mx.core.UIComponent
import mx.controls.CheckBox

class MyRenderer extends UIComponent
{
  var my_ch : MovieClip;
  var my_txt: TextField;

  var listOwner : MovieClip;
  var getCellIndex : Function; 
  var getDataLabel : Function; 

  function MyRenderer(){}
  
  function createChildren(Void) : Void
  {
    my_ch = createObject("CheckBox", "my_ch", 1, {styleName:this, owner:this});
    my_ch.addEventListener("click", this);
    size();
  }
  function size(Void) : Void
  { 
    my_ch.setSize(20, __height);
    my_ch._x = (__width-20)/2;
    my_ch._y = (__height-16)/2;
  }

  function setValue(theValue:String, theItem:Object, selected:String) : Void
  {
    my_ch._visible = (theItem!=undefined);
    my_ch.selected = theItem.state

    my_txt._visible = (theItem!=undefined);
    my_txt.text=theValue;
  }
  
  function click()
  {
  listOwner.dataProvider.editField(getCellIndex().itemIndex, "state", my_ch.selected);
  }
}

There's a mix of old and new material in this example. The result looks like Figure 5.

Figure 5

Figure 5. The text field and dynamically generated check box can appear together in a row of the List component (or cell or a DataGrid component).

First, note you're importing the UIComponent and CheckBox classes and extending the UIComponent class—not the MovieClip object. This gives you access to methods in those classes, and more importantly, a chance to define methods that those classes will now call. For example, at the end of the createChildren() method you trigger the size() method. That's more than just a modular technique—it's because the UIComponent class will call this any time the component changes size (for example, when the user resizes the column widths). Inside the size() method is where you write any code you want triggered when that event occurs.

Probably the easiest part of this example is the setValue() method. You just display the text like normal, and set the my_ch 's selected property. Notice that my_ch was created using createObject() . This is basically the new way you can perform the attachMovie() function—but with components. One last detail to note is that you have access to methods such as getCellIndex() (as shown inside the click() method). The getCellIndex() method returns several useful properties, including itemIndex. You'll also notice inside the click() method that you can grab a reference to the appropriate DataProvider class by referring to the listOwner instance. Finally, all you really wanted to do in the click() method was edit one item in the DataProvider instance. Not one row in the array, not the whole array, but just one cell. The way you should do that is with the editField() method. (This works from inside your main movie too—it's not some special feature of the UIComponent class being extended.)

There are a few more details that you can learn, but this should get you started doing very advanced cell renderers. Check out the example from which this example was drawn in mx.controls.cells (that is, inside the Classes folder adjacent to your installed version of Flash MX 2004, go inside the folder named mx, then inside controls, then cells).

Scrolling Text: Depending on how much you used the old ScrollBar component, you may be in store for some more work. In the end, you may like the TextArea component better. However, migrating involves more than just replacing instances and learning new syntax—there is no replacement so you'll have to restructure your application. Don't worry; it's not quite the end of the world.

First off, you might consider just using the v1 component in your application. I haven't seen this fail in Flash Player 7 ActionScript 2.0, but it's not officially supported. Although the TextArea component includes an automatic scrolling text feature, it's not identical to the old behavior. For example, the scroll bars are only displayed when they are needed. In addition, the old scroll bar enables you to snap on to any TextField component. The TextArea component includes the text field, frame, and a scroll bar of its own.

If you're up for using the new TextArea component (really, it's pretty nice), I can give you a few pointers to get you started. Mainly you'll want to learn how to access and change the available styles. You'll learn more about setting styles individually—per component instance—and globally in the following section. You can search the Flash MX 2004 online help for "Supported Styles" to find them all, but for the TextArea component I find myself setting the borderStyle to "none" (as in myTextArea.setStyle("borderStyle", "none") ). Naturally, you can also format your text using HTML or cascading style sheets (CSS) just like regular TextField components in Flash MX 2004.

An interesting point about the TextArea component is that although most of the text field properties are exposed as properties of the TextArea instance, you may sometimes need to dig into the TextArea instance to control the text it displays. That is, there's a text field inside the TextArea instance called label . Usually, you can just say myTextArea.text="some text" , but for a few cases you'll need to access the label as in myTextArea.label.onChanged=function(){} . (You could always access the label—as in myTextArea.label.text="some text" —but it's usually not necessary to go that deep.)

Styles: There's a lot to say about styles, skinning, and creating entire themes (of related styles) for your components. But insofar as upgrading your old components you only have to be aware of a few things. First the old setStyleProperty() method is effectively replaced with setStyle() . However, where the old setStyleProperty() method was used to affect individual instances, you can use the v2 components' setStyle() method to change all components in your application, all components of a certain type, or just a single instance. To be fair, you could also set styles globally with v1 components, but it was handled through the FStyleFormat() class. Basically, you'd create a class, set properties, and then apply that class to various individual components. The equivalent in the v2 component architecture is the CSSStyleDeclaration() class, which is more consistent with CSS.

What follows are three side-by-side examples using v1 and v2 components to set styles of individual instances, to affect all components, and then using v2 components to set a particular class of component.

  • Setting individual instances:

    //V1
    myFormat =new FStyleFormat();
    myFormat.addListener(myButton);
    myFormat.addListener(myOtherButton);
    
    myFormat.darkshadow=0x1376C7;
    myFormat.highlight=0xE5F4FC;
    myFormat.highlight3D=0xE5F4FC;
    myFormat.shadow=0x1376C7;
    myFormat.face=0xD5FFFF;
    myFormat.applyChanges();
    
    //V2 
    myButton.setStyle("themeColor",0x1376C7);
    myButton.setStyle("color",0xFF0000);
  • Setting all component instances:

    //V1
    globalStyleFormat.darkshadow=0x1376C7;
    globalStyleFormat.highlight=0xE5F4FC;
    //… and so on
    globalStyleFormat.applyChanges();
    //use globalStyleFormat verbatim
    
    //V2 
    _global.style.setStyle("themeColor",0x1376C7);
    _global.style.setStyle("color",0xFF0000);
    //… and so on
    //use _global.style verbatim
  • Setting styles on an individual component type:

    //V2 only:
    var myStyle=new mx.styles.CSSStyleDeclaration();
    myStyle.color=0xFF0000;
    _global.styles.CheckBox=myStyle;

Note that you can also use CSSStyleDeclaration() on individual instances as well as _global.style. Also note that I was only setting a few color styles. There are way more you can use, including text formatting styles.

Another killer style is the easing style for the animated components. For example, the ComboBox component has a style for how it opens and how it closes. Check this out:

myComboBox.setStyle("openEasing", mx.transitions.easing.Bounce.easeOut); 
myComboBox.setStyle("openDuration", 2000);

You'll find other styles available for the ComboBox as well as Tree and other animated components. To find more transitions just snoop through the mx.transitions.easing folder. Not only are these transitions totally cool, but the syntax is consistent with all the other styles.